package testview.zhen.com.myapplication.view;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import java.util.logging.Logger;

import testview.zhen.com.myapplication.R;
import testview.zhen.com.myapplication.tool.AudioRecorder;

@SuppressLint({"HandlerLeak", "AppCompatCustomView"})
public class RecordButton extends Button
{
	private static final String TAG = "RecordButton";

    private final int MIN_RECORD_TIME = 1; // 最短录音时长，单位秒
    private final int MAX_RECORD_TIME = 60; // 最大录音时长，到达时间自动结束录音
    private final int RECORD_OFF = 0; // 不在录音
    private final int RECORD_ON = 1; // 正在录音
    private long startTime = 0;

    private Dialog recordDialog;
    private AudioRecorder audioRecorder;
    private RecorderListener recorderListener;

    private int recordState = 0; // 录音状态
    private int recordTime = 0; // 录音时长(ms)，如果录音时间太短则录音失败
    private double voiceValue = 0.0; // 录音的音量值
    private boolean isCanceled = false; // 是否取消录音
    // private boolean isShowCancel = false; // 是否正在显示可取消录音的提示
    private float downY;

    private TextView dialogTextView, dialogTimeView;
    private ImageView dialogImage;

    public RecordButton(Context context)
    {
	super(context);
	init();
    }

    public RecordButton(Context context, AttributeSet attrs)
    {
	super(context, attrs);
	init();
    }

    public RecordButton(Context context, AttributeSet attrs, int defStyle)
    {
	super(context, attrs, defStyle);
	init();
    }

    private void init()
    {
	// this.setText("按住 说话");
	// setBackgroundResource(R.drawable.voice_recording);
    }

    // 录音时显示Dialog
    private void showVoiceDialog(int flag)
    {

	if (recordDialog == null)
	{
	    recordDialog = new Dialog(getContext(), R.style.record_dialog_style);
	    recordDialog.setContentView(R.layout.dialog_record);
	    // //弹出对话框时不显示系统导航栏
	    // Window dialogWindow = recordDialog.getWindow();
	    // WindowManager.LayoutParams lp = dialogWindow.getAttributes();
	    // dialogWindow.setGravity(Gravity.CENTER);
	    // lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
	    // lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
	    // dialogWindow.setAttributes(lp);
	    dialogImage = (ImageView) recordDialog.findViewById(R.id.record_dialog_image);
	    dialogTextView = (TextView) recordDialog.findViewById(R.id.record_dialog_text);
	    dialogTimeView = (TextView) recordDialog.findViewById(R.id.record_dialog_time);
	}
	switch (flag)
	{
	    case 1:
		dialogImage.setImageResource(R.mipmap.record_cancel);
		dialogTextView.setText("松开手指可取消发送");
		// this.setText("松开取消");
		break;

	    default:
		dialogImage.setImageResource(R.mipmap.record_animate_01);
		dialogTextView.setText("向上滑动可取消发送");
		// this.setText("松开完成");
		break;
	}
	dialogTextView.setTextSize(14);
	// // 隐藏状态栏及虚拟按键
	// recordDialog
	// .getWindow()
	// .getDecorView()
	// .setSystemUiVisibility(
	// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
	// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
	// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
	// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
	// | View.SYSTEM_UI_FLAG_FULLSCREEN
	// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
	recordDialog.show();

    }

    // 录音时间太短时Toast显示
    private void showWarnToast(String toastText)
    {
	Toast toast = new Toast(getContext());
	View warnView = LayoutInflater.from(getContext()).inflate(R.layout.toast_record_warn, null);
	TextView textView = (TextView) warnView.findViewById(R.id.record_warn_toast_text);
	textView.setText(toastText);
	toast.setView(warnView);
	toast.setGravity(Gravity.CENTER, 0, 0);// 起点位置为中间
	toast.show();
    }

    // 开启录音计时线程
    private void callRecordTimeHandler()
    {
	recordTime = 0;
	startTime = System.currentTimeMillis();
	recordHandler.sendEmptyMessageDelayed(0, 100);
    }

    // 录音Dialog图片随录音音量大小切换
    private void setDialogImage()
    {
	// System.out.println("voiceValue = " + voiceValue + "    time = " +
	// System.currentTimeMillis());
	if (voiceValue < 600.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_01);
	}
	else if (voiceValue > 600.0 && voiceValue < 1000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_02);
	}
	else if (voiceValue > 1000.0 && voiceValue < 1200.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_03);
	}
	else if (voiceValue > 1200.0 && voiceValue < 1400.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_04);
	}
	else if (voiceValue > 1400.0 && voiceValue < 1600.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_05);
	}
	else if (voiceValue > 1600.0 && voiceValue < 1800.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_06);
	}
	else if (voiceValue > 1800.0 && voiceValue < 2000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_07);
	}
	else if (voiceValue > 2000.0 && voiceValue < 3000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_08);
	}
	else if (voiceValue > 3000.0 && voiceValue < 4000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_09);
	}
	else if (voiceValue > 4000.0 && voiceValue < 6000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_10);
	}
	else if (voiceValue > 6000.0 && voiceValue < 8000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_11);
	}
	else if (voiceValue > 8000.0 && voiceValue < 10000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_12);
	}
	else if (voiceValue > 10000.0 && voiceValue < 12000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_13);
	}
	else if (voiceValue > 12000.0)
	{
	    dialogImage.setImageResource(R.mipmap.record_animate_14);
	}
    }

    private Handler recordHandler = new Handler()
    {
	private int count0 = 0;

	@Override
	public void handleMessage(Message msg)
	{
	    if (recordState == RECORD_ON)
	    {
		// recordTime += 0.1;
		recordTime = (int) ((System.currentTimeMillis() - startTime) / 1000);
		dialogTimeView.setText((int) (MAX_RECORD_TIME - recordTime) + "s");
		// 获取音量
		voiceValue = audioRecorder.getAmplitude();
		if (!isCanceled)
		{
		    // 更新dialog
		    setDialogImage();
		}
		if (voiceValue <= 0)
		{
		    count0++;
		    Log.e("eee", "count0 = " + count0 + "        recordTime = " + recordTime);
		    if (count0 == 10 && (int) recordTime == 1)
		    {
			// 开头连续1秒没有声音，提示用户设备可能没有授予app录音权限
			recordState = RECORD_OFF;
			if (recordDialog.isShowing())
			{
			    recordDialog.dismiss();
			}
			audioRecorder.stop();
			voiceValue = 0.0;
			isCanceled = false;
			audioRecorder.delete();
			new AlertDialog.Builder(getContext()).setTitle("权限提示")
				.setMessage("麦克风没有声音，可能是App的录音权限被禁止，请在手机的权限管理中将\"" + getContext().getResources().getString(R.string.app_name) + "\"的录音权限设置为允许")
				.setNeutralButton("我知道了", null).show();
			count0 = 0;
			if (recorderListener != null)
			{
			    recorderListener.onRecordCanceled(audioRecorder);
			}
		    }
		}
		else count0 = 0;

		if (recordTime >= MAX_RECORD_TIME)
		{
		    recordState = RECORD_OFF;
		    if (recordDialog.isShowing())
		    {
			recordDialog.dismiss();
		    }
		    audioRecorder.stop();
		    voiceValue = 0.0;
		    isCanceled = false;
		    showWarnToast("时间太长  自动结束");
		    if (recorderListener != null)
		    {
			recorderListener.onRecordEnd(audioRecorder);
		    }
		    // this.setText("按住 说话");
		}
		else sendMessageDelayed(obtainMessage(0), 100);
	    }
	}
    };

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
	switch (event.getAction())
	{
	    case MotionEvent.ACTION_DOWN: // 按下按钮
		if (isEnabled())
		{
		    if (recordState != RECORD_ON)
		    {
			setBackgroundResource(R.mipmap.voice_recording_pressed);
			showVoiceDialog(0);
			downY = event.getY();
			if (audioRecorder != null)
			{
			    audioRecorder.ready();
			    recordState = RECORD_ON;
			    if (recorderListener != null)
			    {
				recorderListener.onRecordStart(audioRecorder);
			    }
			    audioRecorder.start(getContext());
			    callRecordTimeHandler();
			}
		    }
		}
		else
		{
		    if (recorderListener != null)
		    {
			recorderListener.onRecordDisenable(audioRecorder);
		    }
		}
		break;
	    case MotionEvent.ACTION_MOVE: // 滑动手指
		if (recordState == RECORD_ON)
		{
		    float moveY = event.getY();
		    if (downY - moveY > 40)
		    {
			downY = event.getY();
			isCanceled = true;
			showVoiceDialog(1);
		    }
		    else if (downY - moveY < -40)
		    {
			downY = event.getY();
			isCanceled = false;
			showVoiceDialog(0);
		    }
		}
		break;
	    case MotionEvent.ACTION_UP: // 松开手指
		if (recordState == RECORD_ON)
		{
		    setBackgroundResource(R.drawable.voice_recording);
		    recordState = RECORD_OFF;
		    if (recordDialog.isShowing())
		    {
			recordDialog.dismiss();
		    }
		    audioRecorder.stop();
		    voiceValue = 0.0;
		    if (isCanceled)
		    {
			audioRecorder.delete();
			if (recorderListener != null)
			{
			    recorderListener.onRecordCanceled(audioRecorder);
			}
		    }
		    else
		    {
			if (recordTime < MIN_RECORD_TIME)
			{
			    showWarnToast("时间太短  录音失败");
			    audioRecorder.delete();
			    if (recorderListener != null)
			    {
				recorderListener.onRecordCanceled(audioRecorder);
			    }
			}
			else
			{
			    if (recorderListener != null)
			    {
				recorderListener.onRecordEnd(audioRecorder);
			    }
			}
		    }
		    isCanceled = false;
		    // this.setText("按住 说话");
		}
		break;
	    case MotionEvent.ACTION_MASK:
//		System.out.println("ACTION_MASK");
			Log.i(TAG,"ACTION_MASK");
		break;
	    case MotionEvent.ACTION_CANCEL:
//		System.out.println("ACTION_CANCEL");
			Log.i(TAG,"ACTION_CANCEL");
		if (recordState == RECORD_ON)
		{
		    setBackgroundResource(R.drawable.voice_recording);
		    recordState = RECORD_OFF;
		    if (recordDialog.isShowing())
		    {
			recordDialog.dismiss();
		    }
		    audioRecorder.stop();
		    voiceValue = 0.0;
		    isCanceled = false;
		    showWarnToast("时间太短  录音失败");
		    audioRecorder.delete();
		    if (recorderListener != null)
		    {
			recorderListener.onRecordCanceled(audioRecorder);
		    }
		}
		break;
	    case MotionEvent.ACTION_POINTER_UP:
//		System.out.println("ACTION_POINTER_UP");
			Log.i(TAG,"ACTION_POINTER_UP");
		break;
	    case MotionEvent.ACTION_HOVER_EXIT:
//		System.out.println("ACTION_HOVER_EXIT");
			Log.i(TAG,"ACTION_HOVER_EXIT");
		break;
	}
	// return true;
	return super.onTouchEvent(event);
    }

    public int getRecordTime()
    {
	return recordTime;
    }

    public AudioRecorder getAudioRecorder()
    {
	return audioRecorder;
    }

    public void setAudioRecorder(AudioRecorder audioRecorder)
    {
	this.audioRecorder = audioRecorder;
    }

    public void setRecorderListener(RecorderListener recorderListener)
    {
	this.recorderListener = recorderListener;
    }

    public interface RecorderListener
    {
	public void onRecordStart(AudioRecorder audioRecorder);

	public void onRecordEnd(AudioRecorder audioRecorder);

	public void onRecordCanceled(AudioRecorder audioRecorder);

	public void onRecordDisenable(AudioRecorder audioRecorder);
    }
}